package com.industrial.premu.service.impl.sqsj;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuBenefitEvaluationNo;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluationNo;
import com.industrial.premu.dto.PreMuOuterDataImportNoDto;
import com.industrial.premu.mapper.PreMuBenefitEvaluationNoMapper;
import com.industrial.premu.service.IPreMuCompanyInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * description:
 * auth fcb
 * date 2025-08-05 16:09
 **/
@Service
@Slf4j
public class OuterInterfaceService {

    private static final Pattern numberPattern = Pattern.compile("^\\d+(\\.\\d+)?$");

    @Autowired
    private PreMuBenefitEvaluationNoMapper preMuBenefitEvaluationNoMapper;
    @Autowired
    private IPreMuCompanyInfoService preMuCompanyInfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 导入不参评企业数据，直接放入一键汇入表中
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(PreMuOuterDataImportNoDto params) {
        // 1. 检查参数
        AjaxResult ajaxResult = this.checkParams(params);
        if(ajaxResult != null) {
            return ajaxResult;
        }
        // 2. 检查本次提交的数据是否都是规上规下企业
        AjaxResult checkCompanyTypeResult = this.checkCompanyType(params.getData(), params.getCompanyType());
        if(checkCompanyTypeResult != null) {
            return checkCompanyTypeResult;
        }
        // 3. 检查数据的是否正常，记录企业的信用代码
        List<String> usccList = new ArrayList<>();
        AjaxResult checkDataResult = this.checkData(params.getData(), usccList);
        if(checkDataResult != null) {
            return checkDataResult;
        }
        // 4. 获取企业信息
        Map<String, PreMuCompanyInfo> comMap = this.queryCompanyList(params);
        // 5. 获取已经导入过的信息
        Map<String, PreMuBenefitEvaluationNo> noCpExistMap = this.queryExistNoCp(params);
        // 6. 处理数据
        List<PreMuImportBenefitEvaluationNo> updateImportEvaluationNoList = new ArrayList<>();
        List<PreMuImportBenefitEvaluationNo> addImportEvaluationNoList = new ArrayList<>();
        Date now = new Date();
        int addCount = 0;
        int updateCount = 0;
        for(PreMuImportBenefitEvaluationNo temp : params.getData()) {
            temp.setCounty(params.getCounty());
            temp.setYear(Long.valueOf(params.getYear()));
            temp.setStatus("0");
            temp.setDelFlag("0");
            // 计算总用地面积
            if (temp.getSumArea() == null || !numberPattern.matcher(temp.getSumArea() + "").matches() || Double.valueOf(temp.getSumArea()) == 0) {
                BigDecimal sumArea = this.computeSumArea(temp);
                if(sumArea.doubleValue() == 0){
                    return AjaxResult.warn("导入失败：企业【"+temp.getCompanyName() + "】的总用地面积计算后数据为0，请检查导入数据！"+"】");
                }
                temp.setSumArea(sumArea.toString());
            }
            // 设置产业信息
            PreMuCompanyInfo companyInfo = comMap.get(temp.getUscc());
            if(companyInfo != null){
                temp.setIndustryType(companyInfo.getIndustryType());
                temp.setIndustryMediumType(companyInfo.getIndustryMediumType());
            }
            // 已经导入过
            if (noCpExistMap.containsKey(temp.getUscc())) {
                // 对已经存在的数据更新部分信息
                this.setExistNoCpInfo(temp, comMap, noCpExistMap);
                temp.setUpdateDate(now);
                // todo
                //temp.setUpdateBy("");
                updateCount++;
                updateImportEvaluationNoList.add(temp);
            }
            // 没导入过
            else if(comMap.containsKey(temp.getUscc())){
                this.setNoCpInfo(temp, comMap);
                temp.setCreateDate(now);
                // todo
                //temp.setCreateBy("admin");
                addCount++;
                addImportEvaluationNoList.add(temp);
            }
            // 数据库操作
            this.insertOrUpdateData(updateImportEvaluationNoList, addImportEvaluationNoList);
        }
        if(!updateImportEvaluationNoList.isEmpty()){
            preMuBenefitEvaluationNoMapper.batchUpdate(updateImportEvaluationNoList);
            updateImportEvaluationNoList.clear();
        }

        if(!addImportEvaluationNoList.isEmpty()){
            preMuBenefitEvaluationNoMapper.batchSave(addImportEvaluationNoList);
            addImportEvaluationNoList.clear();
        }
        return AjaxResult.success("导入成功，共新增：" + addCount + "条，共更新：" + updateCount + "条");
    }

    private void insertOrUpdateData(List<PreMuImportBenefitEvaluationNo> updateImportEvaluationNoList, List<PreMuImportBenefitEvaluationNo> addImportEvaluationNoList) {
        if(updateImportEvaluationNoList.size() > 100){
            preMuBenefitEvaluationNoMapper.batchUpdate(updateImportEvaluationNoList);
            updateImportEvaluationNoList.clear();
        }

        if(addImportEvaluationNoList.size() > 100){
            preMuBenefitEvaluationNoMapper.batchSave(addImportEvaluationNoList);
            addImportEvaluationNoList.clear();
        }
    }
    private void setNoCpInfo(PreMuImportBenefitEvaluationNo temp, Map<String, PreMuCompanyInfo> comMap) {
        PreMuCompanyInfo preMuCompanyInfo = comMap.get(temp.getUscc());
        temp.setId(UUID.randomUUID().toString().replace("-", ""));
        temp.setDelFlag("0");
        //设置行政区
        String county = temp.getCounty();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(county) && county.length() == 6){
            temp.setProvince(org.apache.commons.lang3.StringUtils.left(county,2) + "0000");
            temp.setProvinceName(redisTemplate.opsForValue().get("area:" + temp.getProvince()));
            temp.setCity(org.apache.commons.lang3.StringUtils.left(county,4) + "00");
            temp.setCityName(redisTemplate.opsForValue().get("area:" + temp.getCity()));
            temp.setCountyName(redisTemplate.opsForValue().get("area:" + temp.getCounty()));
        }

        //设置业企规模名称
        String companyScaleName = DictUtils.getDictLabel("bus_enter_scale", temp.getCompanyScale());
        temp.setCompanyScaleName(companyScaleName);
        //设置企业类型
        String companyType = DictUtils.getDictLabel("enter_type", temp.getCompanyType());
        temp.setCompanyTypeName(companyType);
        //设置行业类型
        String industryTypeName = DictUtils.getDictLabel("industry_names", temp.getIndustryType());
        temp.setIndustryTypeName(industryTypeName);

        if(preMuCompanyInfo != null && org.apache.commons.lang3.StringUtils.isNotBlank(preMuCompanyInfo.getVillage())){
            temp.setVillage(preMuCompanyInfo.getVillage());
            temp.setVillageName(redisTemplate.opsForValue().get("area:" + preMuCompanyInfo.getVillage()));
        }
    }

    private void setExistNoCpInfo(PreMuImportBenefitEvaluationNo temp, Map<String, PreMuCompanyInfo> comMap, Map<String, PreMuBenefitEvaluationNo> noCpExistMap) {
        PreMuCompanyInfo preMuCompanyInfo = comMap.get(temp.getUscc());
        PreMuBenefitEvaluationNo tempObj = noCpExistMap.get(temp.getUscc());
        temp.setId(tempObj.getId());
        temp.setDelFlag("0");
        //设置行政区
        String county = temp.getCounty();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(county) && county.length() == 6){
            temp.setProvince(org.apache.commons.lang3.StringUtils.left(county,2) + "0000");
            temp.setProvinceName(redisTemplate.opsForValue().get("area:" + temp.getProvince()));
            temp.setCity(org.apache.commons.lang3.StringUtils.left(county,4) + "00");
            temp.setCityName(redisTemplate.opsForValue().get("area:" + temp.getCity()));
            temp.setCountyName(redisTemplate.opsForValue().get("area:" + temp.getCounty()));
        }

        //设置业企规模名称
        String companyScaleName = DictUtils.getDictLabel("bus_enter_scale", temp.getCompanyScale());
        temp.setCompanyScaleName(companyScaleName);
        //设置企业类型
        String companyType = DictUtils.getDictLabel("enter_type", temp.getCompanyType());
        temp.setCompanyTypeName(companyType);

        //设置行业类型
        String industryTypeName = DictUtils.getDictLabel("industry_names", temp.getIndustryType());
        temp.setIndustryTypeName(industryTypeName);
        if(preMuCompanyInfo != null && org.apache.commons.lang3.StringUtils.isNotBlank(preMuCompanyInfo.getVillage())){
            temp.setVillage(preMuCompanyInfo.getVillage());
            temp.setVillageName(redisTemplate.opsForValue().get("area:" + preMuCompanyInfo.getVillage()));
        }

    }

    // 查询企业信息
    private Map<String, PreMuCompanyInfo> queryCompanyList(PreMuOuterDataImportNoDto params) {
        //企业基本信息
        Map<String, PreMuCompanyInfo> comMap = new HashMap<>(128);
        PreMuCompanyInfo companyInfoQueryParams = new PreMuCompanyInfo();
        companyInfoQueryParams.setCompanyType(params.getCompanyType());
        companyInfoQueryParams.setCounty(params.getCounty());
        companyInfoQueryParams.setYear(params.getYear());
        List<PreMuCompanyInfo> list = preMuCompanyInfoService.list(companyInfoQueryParams);
        if(CollectionUtil.isNotEmpty( list)) {
            list.forEach(item -> {
                if (item.getUscc() != null && !"".equals(item.getUscc())) {
                    comMap.put(item.getUscc(), item);
                }
            });
        }
        return comMap;
    }

    // 查询已经导入的非参评企业的数据
    private Map<String, PreMuBenefitEvaluationNo> queryExistNoCp(PreMuOuterDataImportNoDto params) {
        Map<String, PreMuBenefitEvaluationNo> noCpExistMap = new HashMap<>();
        PreMuBenefitEvaluationNo queryNoCp = new PreMuBenefitEvaluationNo();
        queryNoCp.setCounty(params.getCounty());
        queryNoCp.setCompanyType(params.getCompanyType());
        queryNoCp.setYear(params.getYear());
        List<PreMuBenefitEvaluationNo> preMuBenefitEvaluationNos = preMuBenefitEvaluationNoMapper.selectPreMuBenefitEvaluationNoList(queryNoCp);
        if(CollectionUtil.isNotEmpty(preMuBenefitEvaluationNos)) {
            preMuBenefitEvaluationNos.forEach(item -> {
                if (item.getUscc() != null && !"".equals(item.getUscc())) {
                    noCpExistMap.put(item.getUscc(), item);
                }
            });
        }
        return noCpExistMap;
    }

    // 计算总用地面积
    private BigDecimal computeSumArea(PreMuImportBenefitEvaluationNo mcImportBenefitEvaluationDO) {
        BigDecimal userArea = new BigDecimal(0);
        BigDecimal otherArea = new BigDecimal(0);
        BigDecimal leasedArea = new BigDecimal(0);
        BigDecimal rentOutArea = new BigDecimal(0);
        BigDecimal sumArea = new BigDecimal(0);

        if(mcImportBenefitEvaluationDO.getUseArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getUseArea()+"").matches()){
            userArea = new BigDecimal(mcImportBenefitEvaluationDO.getUseArea()+"");
        }
        if(mcImportBenefitEvaluationDO.getOtherArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getOtherArea()+"").matches()){
            otherArea = new BigDecimal(mcImportBenefitEvaluationDO.getOtherArea()+"");
        }
        if(mcImportBenefitEvaluationDO.getLeasedArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getLeasedArea()+"").matches()){
            leasedArea = new BigDecimal(mcImportBenefitEvaluationDO.getLeasedArea()+"");
        }
        if(mcImportBenefitEvaluationDO.getRentOutArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getRentOutArea()+"").matches()){
            rentOutArea = new BigDecimal(mcImportBenefitEvaluationDO.getRentOutArea()+"");
        }
        sumArea = userArea.add(otherArea).add(leasedArea).subtract(rentOutArea);
        return sumArea;
    }


    private AjaxResult checkData(List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos, List<String> usccList) {
        for(int i=0;i<preMuImportBenefitEvaluationNos.size();i++){
            PreMuImportBenefitEvaluationNo data = preMuImportBenefitEvaluationNos.get(i);
            if (data.getUscc() != null && !"".equals(data.getUscc())){
                usccList.add(data.getUscc().trim());
                if("1".equals(data.getCompanyType())){
                    if(data.getMainIncome() == null) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->营业收入为空或异常，请检查导入数据！");
                    }

                    String totalUsed = data.getTotalUsed();
                    BigDecimal totalUsedBigDecimal = StringUtils.isBlank(totalUsed) ? BigDecimal.ZERO : new BigDecimal(totalUsed);

                    if(totalUsedBigDecimal.compareTo(BigDecimal.ZERO) < 0) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->总耗能为空或异常，请检查导入数据！");
                    }
                    if(data.getRdFunds() == null) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->研发经费支出为空或异常，请检查导入数据！");
                    }
                    if(data.getTotalEquivalent() == null) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->排放总当量为空或异常，请检查导入数据！");
                    }
                    if(data.getIndustryOutput() == null) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->工业总产值为空或异常，请检查导入数据！");
                    }
                    if(data.getAnnualEmployees() == null || data.getAnnualEmployees() < 0L) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->年平均职工人数为空或异常，请检查导入数据！");
                    }
                    if(data.getProfitTotal() == null) {
                        return AjaxResult.warn("导入失败：" + data.getCompanyName() + "->利润总额为空，请检查导入数据！");
                    }
                }
            }

        }
        long count = usccList.stream().distinct().count();
        boolean isRepeat = count < usccList.size();
        if (isRepeat) {
            return AjaxResult.warn("有重复统一社会信用代码，请检查导入数据！");
        }
        return null;
    }


    private AjaxResult checkCompanyType(List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos, String companyType) {
        List<String> list = new ArrayList<>(20);
        for(PreMuImportBenefitEvaluationNo t : preMuImportBenefitEvaluationNos){
            if(!StringUtils.equals(t.getCompanyType(), companyType)){
                list.add(t.getCompanyName());
            }
        }
        if(!list.isEmpty()) {
            return AjaxResult.warn("以下企业类型【规上或规下】与您导入时所填企业类型不符：" + String.join("、", list));
        }
        return null;
    }

    private AjaxResult checkParams(PreMuOuterDataImportNoDto params) {
        if (StrUtil.isBlank(params.getCompanyType()) || (!"1".equals(params.getCompanyType()) && !"2".equals(params.getCompanyType()))) {
            return AjaxResult.warn("参数错误：未知的企业类型");
        }
        if (StrUtil.isBlank(params.getYear())) {
            return AjaxResult.warn("参数错误：年份不能为空");
        }
        if (CollectionUtil.isEmpty(params.getData())) {
            return AjaxResult.warn("参数错误：导入数据不能为空");
        }
        if(StrUtil.isBlank(params.getCounty())) {
            return AjaxResult.warn("参数错误：区县代码不能为空");
        }
        return null;
    }
}
